/**
 * WeeShop 声明
 * ===========================================================
 * 网站： https://www.darlang.com
 * 标题： ECShop 小程序「weeshop 」- 基于 ECShop 为后台系统开发的非官方微信商城小程序
 * 链接： https://www.darlang.com/?p=709
 * 说明： 源码已开源并遵循 Apache 2.0 协议，你有权利进行任何修改，但请保留出处，请不要删除该注释。
 * ==========================================================
 * Copyright 2019 darlang
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ===========================================================
 */

// detail.js
import { PNT, setNavBarTitle, showToast, shopUrl, formatLeftTime, getCurrentPageUrl, pushPagePath, formatTime } from "../../utils/utils";
import { TeamDetail, ChangeFavoriteStatus, GetCheckShop, CheckTeam } from '../../utils/apis';
import { CheckCartTotal } from "../../utils/publics";
import WxParse from "../../libs/wxParse/wxParse.js";
var inter;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    id: 0,
    goods: {},// 商品信息
    propertyPopState: false,// 规格弹窗
    curProperty: '',// 当前选中的规格
    curGoodsPrice: '',
    curGoodsStock: 10,
    curStockState: true,// 规格是否通过
    curGoodsNum: 1,// 当前商品购买数量
    cartGoodsSum: 0,// 购物车数量
    isLiked: false,// 是否收藏
    goodsAccLst: '',// 商品关联附件
    consignee: '',// 收货地址
    commentsTotal: 0,
    goods_attr:0,
    commentsPreview: {
      grade:3,
      updated_at:'2019-10-10',
    },//
    info:{
      thumb:[
        {
        id:1,
        img_original:'images/201703/goods_img/_P_1490147631627.jpg',
      },
        {
          id: 2,
          img_original: 'images/201703/goods_img/_P_1490147631627.jpg',
        },
      ],
      goods:{
        goods_name:'Galanz/格兰仕 G80F23CN3L-C2(R0)正品微波炉23L 智能光波炉家用 800w速热23升容量1级能效智能预约',
        shop_price:200.88,
        discount:4.1,
        market_price:300.14,
        sales_volume:20,
        goods_number:100,
        tj:88.41,
        rs:2,
      },
      shop:{
        logo:'https://donglongshangshi.oss-cn-beijing.aliyuncs.com/seller_imgs/seller_logo/logo_thumb/1490146939391305403.jpg',
        name:'万卓旗舰店',
        gz:10,
        s11:5,
        s12:98,
        s21:4,
        s22:100,
        s31:3,
        s32:88,
      },
      comment: [
        {
          user_pic: 'https://donglongshangshi.com/mobile/public/img/user_default.png',
          user_name: '詹丹',
          updated_at: '2019-10-10',
          grade:4,
          content: '哒哒哒哒哒哒过过过过或或',
        },

      ],
    },
    ptxp:[
      
      {
        thumb: 'https://donglongshangshi.oss-cn-beijing.aliyuncs.com/images/201703/goods_img/0_G_1490147626763.jpg',
        name: '炉23L 智能光波炉家用 800w速热23升容量1级能效智能预约',
        price: 20.24,

      },
    ],

    
    attr: [
      {
        attr_name:'哒哒哒哒哒哒多多多',
      }
    ],
    user_id:0,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (opt) {
     console.log(opt)
     setNavBarTitle(PNT.goods.detail);
     this.loginModal = this.selectComponent("#login-modal");
     this.setData({
       id: parseInt(opt.id)
     });
    // this.getCartSum();
    // this.getGoodsAccLst();
    this.getProductInfo();
    // this.checkTeam();
  },
  jumpTo: function (e) {
    // 获取标签元素上自定义的 data-opt 属性的值
    let target = e.currentTarget.dataset.opt;
    this.setData({
      toView: target
    })
  },

  //用户点击tab时调用
  titleClick: function (e) {
    let currentPageIndex =
      this.setData({
        //拿到当前索引并动态改变
        currentIndex: e.currentTarget.dataset.idx
      })
  },
  /**
   * 登录回调
   * @author darlang
   */
  loginCallback(cb) {
    if (cb.detail.type === 'success') {
      // this.getCartSum();
      this.getProductInfo();
      // this.getConsignees();
    }
  },

  /**
   * 
   * 检测是否有地址
   */
  checkUrl() {

    var info = wx.getStorageSync('userInfo');
    GetCheckUrl(info.user_id).then(res => {
      console.log(res.data)
      return res.data;
    })
  },
// 保证弹出和关闭
  showbz: function () {
    this.setData({
      isRuleTrue: true
    })
  },
  hidebz: function () {
    this.setData({
      isRuleTrue: false
    })
  },
  //规则
  showgz: function () {
    var that = this;
    if (that.data.editTrue == true) {
      that.setData({
        editTrue: false,
       
      })

    } else {
      that.setData({
        editTrue: true,
       
      })
    }
  },
  detail(e){
    wx.redirectTo({
      url: '/pages/team/detail?id='+e.currentTarget.dataset.id,
    })
  },
  /**
   * 获取商品
   * @author darlang
   */
  getProductInfo() {
    let self = this;
    var data = {};
    data.id = this.data.id;
    data.user_id = this.data.user_id;
    TeamDetail(data).then(res=>{
      console.log(res)
      self.setData({
        info:res.data,
        teamNew:res.teamNew,
        isLiked:res.data.collect,
        teamlist:res.teamUser,
        comment:res.comment,
        attr_spec:res.attr_spec.pro[""],
      })
      if(res.teamUser.length  > 0){
          this.countDown();
      }
      WxParse.wxParse("goodsDetail", "html", res.data.goods_desc, self);
    })

    
  },

  countDown() {//倒计时函数
    // 获取当前时间，同时得到活动结束时间数组
    let newTime = new Date().getTime();
    var list = this.data.teamlist;
    for(var i = 0;i<list.length;i++){

    
      let endTimeList = list[i].end_time;
    // let countDownArr = [];

    // 对结束时间进行处理渲染到页面
    // endTimeList.forEach(o => {
    // let endTime = new Date(o).getTime();
    let endTime = endTimeList * 1000;
    let obj = null;
    // 如果活动未结束，对时间进行处理
    if (endTime - newTime > 0) {
      let time = (endTime - newTime) / 1000;
      // 获取天、时、分、秒
      // let day = parseInt(time / (60 * 60 * 24));
      let hou = parseInt(time / 3600);
      let min = parseInt(time % 3600 / 60);
      let sec = parseInt(time % 3600 % 60);
      list[i].time = hou+":"+min+":"+sec;
      // obj = {
      //   // day: this.timeFormat(day),
      //   hou: hou,
      //   min: min,
      //   sec: sec
      // }
    } else {//活动已结束，全部设置为'00'
      list.splice(i,1);
    }

    }
    // countDownArr.push(obj);
    // })
    // 渲染，然后每隔一秒执行一次倒计时函数
    this.setData({ teamlist: list })
    inter = setTimeout(this.countDown, 1000);
  },


  /**
   * 活动倒计时
   * @author darlang
   * @param  {Date}   time 时间
   */
  checkGoodsDiscountTime(time) {
    if (this.data.goodsDiscountTime) {
      setTimeout(() => {
        this.setData({
          goodsDiscountTime: formatLeftTime(time)
        });
        this.checkGoodsDiscountTime(time);
      }, 1e3);
    }
  },

  /**
   * 关闭/开启弹窗
   * @author darlang
   */
  switchPopstate() {
    this.setData({
      propertyPopState: !this.data.propertyPopState
    });
  },

  /**
   * 弹出选择规格
   * @author darlang
   */
  changeProSele() {
    // if (!this.loginModal.check()) {
    //   return false;
    // }
    // let g = this.data.goods;
    // let pro = g.properties;
    // let stock = g.stock;
    this.setData({
      propertyPopState: true
    });
  },

  
  /**
   * 修改商品数量
   * @author darlang
   */
  changeGoodsNum(e) {
    let type = e.currentTarget.dataset.type;
    let curGoodsNum = this.data.curGoodsNum;
    console.log(curGoodsNum)
    let curGoodsStock = this.data.curGoodsStock;
    if (type === 'add') {
      curGoodsNum++;
      if (curGoodsNum > 10 && curGoodsNum <= curGoodsStock) {
        showToast('该商品限购10件');
        curGoodsNum = 10;
      } else {
        if (curGoodsNum >= curGoodsStock) {
          showToast('该商品限购10件');
          curGoodsNum = curGoodsStock;
        }
      }
    }
    if (type === 'cut') {
      curGoodsNum--;
      if (curGoodsNum < 1) {
        showToast('请至少选择一件商品');
        curGoodsNum = 1;
      }
    }

    if (type === 'input') {
      curGoodsNum = e.detail.value;
      if (curGoodsNum > 10 && curGoodsNum <= curGoodsStock) {
        showToast('该商品限购10件');
        curGoodsNum = 10;
      } else {
        if (curGoodsNum > curGoodsStock) {
          showToast('该商品限购10件');
          curGoodsNum = curGoodsStock;
        } else {
          if (curGoodsNum < 1) {
            showToast('请至少选择一件商品');
            curGoodsNum = 1;
          }
        }
      }
    }

    this.setData({
      curGoodsNum: curGoodsNum
    });
  },


  /**
   * 收藏/取消收藏
   * @author darlang
   */
  switchCollect() {
    if (!this.loginModal.check()) {
      return false;
    }
    var info = wx.getStorageSync('userInfo')
    let isLiked = this.data.isLiked || false;
    ChangeFavoriteStatus(this.data.info.goods_id, info.user_id).then(res => {
      if (isLiked) {
        isLiked = false;
      } else {
        isLiked = true;
      }
      this.setData({
        isLiked: isLiked
      });
    });
  },

  /**
   * 页面跳转
   * @author darlang
   */
  pushPath(e) {
    const items = e.currentTarget.dataset;
    const pathData = [
      { type: 'cart', path: '/pages/shopping/cart/cart' },
      { type: 'comments', path: '/pages/member/comment/list/list?goodsId=' + items.id }
    ];
    if (items.type === 'home') {
      wx.reLaunch({
        url: '/pages/index/index'
      });
      return false;
    }
    pushPagePath(e, pathData);
  },



  
  /**
   * 下单/立即购买
   * @author mrsq
   */
  goodsShopping(e) {
    if(!this.loginModal.check()){
      return false;
    }
    var that = this;
    var goods_id = that.data.info.goods_id;
    var goods_attr = that.data.goods_attr;
    var num = that.data.curGoodsNum;
    if (!goods_id || !num) {
      showToast("请选择数量", "fail");
      return;
    }
    var data = {};
    var info = wx.getStorageSync('userInfo');
    data.user_id = info.user_id;
    data.goods_attr = goods_attr;
    data.goods_id = goods_id;
    data.num = num;
    var items = e.currentTarget.dataset;
    if(items.type){
      data.type = items.type;
      data.id = that.data.info.id;
    }else{
      data.type = 'goods';
    }
    if(items.team_id){
      data.team_id = items.team_id;
    }
    GetCheckShop(data).then(res => {
      if (res.error_code == 10000) {
        data = JSON.stringify(data);
        wx.navigateTo({
          url: '/pages/shopping/checkout/checkout?preOrder=' + data
        });

      } else {
        wx.showToast({
          title: res.msg,
          icon:'none'
        })
        // showToast(res.msg, "fail");
      }
    })

  },
  /**
   * 检测拼团
   * @author darlang
   */
  checkTeam(){
    var data = {};
    data.id = this.data.info.id;
    CheckTeam(data).then(res=>{
      if(res.data.length > 0){
        this.setData({
          teamlist:res.data,
        })
      }
    })
  },

  /**
   * 获取默认收货人,无默认选择第一条
   * @author darlang
   */
  getConsignees() {
    let consignee = '';
    GetConsigneeList().then(res => {
      if (res.consignees && res.consignees.length > 0) {
        for (let i = 0; i < res.consignees.length; i++) {
          let item = res.consignees[i];
          if (item.is_default) {
            consignee = item.id;
            break;
          } else {
            if (i + 1 === res.consignees.length) {
              consignee = res.consignees[0].id;
            }
          }
        }
      }
      this.setData({
        consignee: consignee
      });
    });
  },

  /**
   * 商品评论 - 只拿一条评论
   * @author darlang
   */
  getGoodsComments() {
    GetCommentList(this.data.id, 1, 1).then(res => {
      if (res.reviews && res.reviews.length > 0) {
        res.reviews[0].updated_at = formatTime(res.reviews[0].updated_at, "Y-M-D");
        res.reviews[0].content = res.reviews[0].content.replace(/^\s*$/g, '');
        if (res.reviews[0] && !res.reviews[0].grade) {
          res.reviews[0].grade = 0;
        }
        this.setData({
          "commentsTotal": res.paged.total,
          "commentsPreview": res.reviews[0]
        });
      }

    });
  },

  /**
   * 背景滚动事件
   * @author darlang
   */
  preventTouchMove(e) {
    console.log(e);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // 页面渲染完成
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 页面显示
    // this.getProductInfo();
    // this.getGoodsComments();
    // this.getConsignees();
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    clearTimeout(inter)
    // 页面隐藏
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearTimeout(inter)
    // 页面关闭
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: this.data.goods.name || PNT.default,
      imageUrl: this.data.goods.default_photo.large || '/images/default_image.png',
      path: getCurrentPageUrl(),
      success() { },
      fail() { },
      complete() { }
    };
  }
});